package com.company.servicename.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.tomcat.util.http.fileupload.IOUtils;

/**
 * @author fangsong.zhang
 * @date 2019/9/25 14:57
 * Copyright zfs
 * 类说明:
 */
public class FileUtil {
    private FileUtil() {
    }

    private static final Logger logger = Logger.getLogger(FileUtil.class);

    /**
     * 通过流下载文件
     *
     * @param resp        响应体
     * @param inputStream 文件流
     * @param fileName    文件名
     */
    public static void download(HttpServletResponse resp, InputStream inputStream, String fileName) {
        resp.setHeader("content-type", "application/octet-stream");
        resp.setContentType("application/octet-stream");
        try {
            resp.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }
        try {
            IOUtils.copyLarge(inputStream, resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("下载文件-{" + fileName + "}-失败");
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    /**
     * 是否为图片格式
     *
     * @param file 文件
     * @return 判断结果
     */
    public static boolean isImgFile(File file) {
        if (file.isDirectory()) {
            return false;
        }
        String fileName = file.getName();
        return isImgFile(fileName);
    }

    /**
     * 是否为图片格式
     *
     * @param fileName 文件名
     * @return 判断结果
     */
    public static boolean isImgFile(String fileName) {
        String suffix = fileExt(fileName);
        return Constant.IMG_SUFFIXES.contains(suffix.toLowerCase() + ",");
    }

    /**
     * 提取文件后缀
     *
     * @param fileName 文件名
     * @return 后缀
     */
    public static String fileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
